package manager

import (
	"net/http"
	"time"

	"github.com/labstack/echo"

	"m-project-admin/app/utils"
)

func GetCurrentAdminId(c *echo.Context) string {
	cookie, err := (*c).Cookie("admin_session_id")
	if err != nil {
		return ""
	}
	value := cookie.Value
	base64Bytes, err := utils.Base64Decode([]byte(value))
	decodeBytes, err := utils.RsaDecrypt(base64Bytes)
	if err != nil {
		return ""
	}

	adminId := string(decodeBytes)
	return adminId
}

func SetAdminCookie(c *echo.Context, b []byte) {
	encodeBytes, err := utils.RsaEncrypt(b)
	if err != nil {
		return
	}
	base64Bytes := utils.Base64Encode(encodeBytes)

	host := (*c).Request().Host

	cookie := new(http.Cookie)
	cookie.Name = "admin_session_id"
	cookie.Value = string(base64Bytes)
	cookie.Path = "/"
	cookie.Domain = host
	cookie.Expires = time.Now().Add(24 * time.Hour)
	(*c).SetCookie(cookie)
}

func DeleteAdminCookie(c *echo.Context) {
	host := (*c).Request().Host

	cookie := new(http.Cookie)
	cookie.Name = "admin_session_id"
	cookie.Value = ""
	cookie.Path = "/"
	cookie.Domain = host
	cookie.Expires = time.Now().AddDate(-1, 0, 0)
	(*c).SetCookie(cookie)
}

// 获取登录管理员信息
func GetLoginAdminInfo(c *echo.Context) map[string]interface{} {
	adminId := GetCurrentAdminId(c)
	adminInfo := getAdminInfo(adminId)
	return adminInfo
}

func getAdminInfo(adminId string) map[string]interface{} {
	adminInfo := make(map[string]interface{})
	admin, _, err := GetAdminById(adminId)
	if err != nil {
		return adminInfo
	}

	adminInfo["id"] = admin.Id.Hex()
	adminInfo["account"] = admin.Account
	adminInfo["name"] = admin.Name
	adminInfo["phone"] = admin.Phone
	adminInfo["is_super"] = admin.Is_super
	adminInfo["status"] = admin.Status

	return adminInfo
}
